package org.apache.dolphinscheduler.alert.plugin;

import cn.hutool.http.HttpUtil;
import org.apache.dolphinscheduler.alert.utils.PropertyUtils;
import org.apache.dolphinscheduler.plugin.api.AlertPlugin;
import org.apache.dolphinscheduler.plugin.model.AlertInfo;
import org.apache.dolphinscheduler.plugin.model.PluginName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * hrt 短信报警插件
 */
public class SmsAlertPlugin implements AlertPlugin {

    private static final Logger logger = LoggerFactory.getLogger(SmsAlertPlugin.class);

    private PluginName pluginName;

    public SmsAlertPlugin(){
        this.pluginName = new PluginName();
        this.pluginName.setEnglish("sms");
        this.pluginName.setChinese("短信");
    }

    @Override
    public String getId() {
        return "sms";
    }

    @Override
    public PluginName getName() {
        return pluginName;
    }

    /**
     * 对告警消息调用发送短信的接口
     * @param info
     * @return
     */
    @Override
    public Map<String, Object> process(AlertInfo info) {
        try {
            String phone=info.getAlertData().getTitle();
            String content=info.getAlertData().getContent();
            String httpAddr=PropertyUtils.getString("alert.sms.addr");

            logger.info(phone+":"+httpAddr);

            StringBuffer sb=new StringBuffer();
            for(String msg:content.split(",")){
                if(msg.contains("name")||msg.contains("state")){
                    sb.append(msg.split(":")[1].replaceAll("\"","")).append("|");
                }
            }
            // 发送短信
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("phone", phone);
            paramMap.put("msg","hello:"+sb.toString()+",please deal it");
            HttpUtil.post(httpAddr, paramMap);
            logger.info("sms http interface call finish");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
